<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.push('/user')"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center  @click="$refs.imgRef.click()">
        <template #default>
          <van-image round class="avatar" :src="userProfile.photo" />
          <input type="file" accept="image/*" @change="onAvatarChange" ref="imgRef" v-show="false">
        </template>
      </van-cell>
      <van-cell
        title="名称"
        is-link
        :value="userProfile.name"
        @click="onNameClick"
      />
      <van-cell
        title="生日"
        is-link
        :value="userProfile.birthday"
        @click="onBirthClick"
      />
    </van-cell-group>
    <!-- 修改用户名称的对话框 -->
    <van-dialog
      v-model="showNameDialog"
      title="修改名称"
      show-cancel-button
      :before-close="beforeClose"
    >
      <van-field
        v-model="name"
        placeholder="请输入用户名"
        input-align="center"
        maxlength="7"
        ref="nameRef"
      />
    </van-dialog>
    <!-- 修改出生日期 -->
    <van-action-sheet v-model="showBirthSheet">
      <van-datetime-picker @cancel='showBirthSheet=false' @confirm='onConfirm'
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-action-sheet>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import { editUserProfileAPI, updateAvatarAPI } from '@/api/userapi.js'
import dayjs from 'dayjs'
export default {
  name: 'UserEdit',
  data () {
    return {
      showNameDialog: false,
      name: '',
      showBirthSheet: false,
      currentDate: new Date(),
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(2050, 0, 1)
    }
  },
  created () {
    this.initUserProfile()
  },
  computed: {
    ...mapState(['userProfile'])
  },
  methods: {
    ...mapActions(['initUserProfile']),
    onNameClick () {
      this.name = this.userProfile.name
      this.showNameDialog = true
      // dom更新完成之后
      this.$nextTick(() => {
        this.$refs.nameRef.focus()
      })
    },
    beforeClose (action, done) {
      // 如果点击取消，关闭弹窗，
      if (action === 'cancel') return done()
      // 如果点击确认，
      // 判断，如果字符非法
      if (this.name.length > 7 || this.name === '') {
        // 弹出提醒
        this.$notify({ type: 'warning', duration: 2000, message: '名称长度必须在1-7位' })
        // 始终获取焦点
        this.$refs.nameRef.focus()
        done(false)
        return
      }
      this.updateUserProfile(done)
    },
    async updateUserProfile (done) {
      try {
        const { data: res } = await editUserProfileAPI({ name: this.name })
        if (res.message === 'OK') {
          done()
          this.initUserProfile()
          this.$notify({ type: 'success', duration: 2000, message: '更新成功' })
        }
      } catch (e) {
        // 这里的e表示捕捉到的错误事件
        if (e.response.status === 409) {
          this.$notify({ type: 'warning', duration: 2000, message: '名称被占用，请重新输入后尝试' })
          done(false)
          this.$refs.nameRef.focus()
        } else {
          this.$notify({ type: 'danger', duration: 2000, message: '更新失败，请检查后尝试' })
          done(false)
        }
      }
    },
    // 出生日期选择
    onBirthClick () {
      if (this.userProfile.birthday) {
        this.currentDate = new Date(this.userProfile.birthday)
      } else {
        this.currentDate = new Date()
      }
      this.showBirthSheet = true
      // 初始化到当前日期
    },
    async onConfirm (val) {
      // 关闭actionsheet弹窗
      this.showBirthSheet = false
      // 对时间数据进行处理
      const dateStr = dayjs(val).format('YYYY-MM-DD')
      // 发送修改数据请求
      const { data: res } = await editUserProfileAPI({ birthday: dateStr })
      // 请求成功，
      if (res.message === 'OK') {
        // 重置用户数据
        this.initUserProfile()
        // 提示用户
        this.$notify({ type: 'success', duration: 2000, message: '更新成功' })
      }
    },
    async onAvatarChange (e) {
      // 处理图片
      const img = e.currentTarget.files
      const fd = new FormData()
      if (img.length === 0) return
      fd.append('photo', img[0])
      const { data: res } = await updateAvatarAPI(fd)
      if (res.message === 'OK') {
        this.$notify({ type: 'success', duration: 2000, message: '更新成功' })
        this.initUserProfile()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
}

.user-edit-container {
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>
